﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Collections.ObjectModel;

namespace LearnMAUI2.ViewModels;

public class QueryPageViewModel : ObservableObject
{
    public ObservableCollection<FilterViewModel> FilterViewModels { get; } = new();

    public QueryPageViewModel()
    {
        //临时填充
        FilterViewModels.Add(new FilterViewModel(this));
    }
    //virtual用于单元测试，add必须知道顺序以便按顺序添加
    public virtual void AddFilterViewModel(FilterViewModel filterViewModel) =>
        FilterViewModels.Insert(FilterViewModels.IndexOf(filterViewModel) + 1, new FilterViewModel(this));

    //demo不能一个都没有
    public virtual void RemoveFilterViewModel(FilterViewModel filterViewModel)
    {
        FilterViewModels.Remove(filterViewModel);
        if (FilterViewModels.Count == 0)
            FilterViewModels.Add(new FilterViewModel(this));
    }
    
}

//内嵌ViewModel
public class FilterViewModel : ObservableObject
{
    //必须持有父级对象才能添加FilterViewModel
    private readonly QueryPageViewModel _queryPageViewModel;

    private string _content;

    //command
    private Lazy<RelayCommand> _lazyAddCommand;
    private Lazy<RelayCommand> _lazyDeleteCommand;

    //它不是MVVM，仅限于QueryPageViewModel使用，不影响其他model，不会对整体MVVM造成影响
    public FilterViewModel(QueryPageViewModel queryPageViewModel)
    {
        _lazyAddCommand = new Lazy<RelayCommand>(new RelayCommand(Add));
        _lazyDeleteCommand = new Lazy<RelayCommand>(new RelayCommand(Delete));
        _queryPageViewModel= queryPageViewModel;
    }

    public string Content
    {
        get => _content;
        set => SetProperty(ref _content, value);
    }

    public RelayCommand AddCommand => _lazyAddCommand.Value;
    public RelayCommand DeleteCommand => _lazyDeleteCommand.Value;

    public void Add() 
    {
        //实际上还是原理的外部ViewModel操作
        _queryPageViewModel.AddFilterViewModel(this);
    }
    public void Delete() 
    {
        _queryPageViewModel.RemoveFilterViewModel(this);
    }
}